package com.lagou.niancheng.rpc.client.netty;

import com.lagou.niancheng.rpc.client.Connection;
import com.lagou.niancheng.rpc.common.converter.Converter;
import com.lagou.niancheng.rpc.common.entity.HostPortMetaData;
import com.lagou.niancheng.rpc.common.entity.SimpleRpcProtocol;
import com.lagou.niancheng.rpc.common.entity.SimpleRpcProtocolBuilder;
import io.netty.channel.Channel;

/**
 * com.lagou.niancheng.rpc.client.netty.NettyConnection
 *
 * @author 大犬
 * @date 2020/5/1
 */
public class NettyConnection implements Connection {

    private Channel channel;
    private Converter converter;
    private RequestResultRegistry requestResultRegistry;
    private long waitResultTimeout;
    private HostPortMetaData hostPortMetaData;

    public NettyConnection(Channel channel,
                           Converter converter,
                           HostPortMetaData hostPortMetaData,
                           RequestResultRegistry requestResultRegistry,
                           long waitResultTimeout) {
        this.channel = channel;
        this.converter = converter;
        this.requestResultRegistry = requestResultRegistry;
        this.waitResultTimeout = waitResultTimeout;
        this.hostPortMetaData = hostPortMetaData;
    }

    @Override
    public Object sendRequestData(Object requestParam) {
        SimpleRpcProtocol requestData = SimpleRpcProtocolBuilder.buildSuccessProtocolData(requestParam, converter);
        channel.writeAndFlush(requestData);
        return requestResultRegistry.waitForResult(channel, waitResultTimeout);
    }


    public Converter getConverter() {
        return converter;
    }

    public void setConverter(Converter converter) {
        this.converter = converter;
    }

    public long getWaitResultTimeout() {
        return waitResultTimeout;
    }

    public void setWaitResultTimeout(long waitResultTimeout) {
        this.waitResultTimeout = waitResultTimeout;
    }

    public HostPortMetaData getHostPortMetaData() {
        return hostPortMetaData;
    }

    public void setHostPortMetaData(HostPortMetaData hostPortMetaData) {
        this.hostPortMetaData = hostPortMetaData;
    }
}
